import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:signage/app/modules/cast/controllers/cast_controller.dart';
import 'package:signage/app/modules/device/controllers/device_controller.dart';
import 'package:signage/app/services/bluetooth_service.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';

class AddDeviceController extends GetxController {
  final DeviceController deviceController = Get.find<DeviceController>();
  late final String currentGroup;
  late final String currentGroupId;
  final BluetoothManager bluetoothManager = Get.find<BluetoothManager>();
  late final String type;
  late final String from;

  // 默认分组Id
  static const String defaultGroupId = '0';
  @override
  void onInit() {
    super.onInit();
    currentGroup = Get.arguments['group'].toString().isEmpty
        ? AppLocalizations.of(Get.context!)!.translate('default_group')
        : Get.arguments['group'].toString();
    currentGroupId = Get.arguments['groupId'].toString().isEmpty
        ? defaultGroupId
        : Get.arguments['groupId'].toString();
    print('currentGroup: $currentGroup');
    type = Get.arguments['type'] ?? 'bluetooth';
    from = Get.arguments['from'] ?? '';
    if (type == 'nfc') {
      bluetoothManager.initNfc();
    } else {
      bluetoothManager.checkPermissionAndStartScan();
    }
  }

  @override
  void onClose() {
    // bluetoothManager.connectedDevices.clear();
    super.onClose();
  }

  final selectedDevices = <String>[].obs;

  Future<void> onDeviceSelected(String deviceId) async {
    try {
      if (selectedDevices.contains(deviceId)) {
        selectedDevices.remove(deviceId);
      } else {
        selectedDevices.add(deviceId);
      }
      selectedDevices.refresh();
    } catch (e, stackTrace) {
      ToastUtils.showError(e.toString());
    }
  }

  Future<void> selectedAllDevices() async {
    if (type == 'nfc') {
      selectedDevices.value =
          bluetoothManager.nfcScanResults.map((e) => e.id).toList();
    } else {
      selectedDevices.value = bluetoothManager.connectedDevices
          .map((e) => e.id.toString())
          .toList();
    }
    selectedDevices.refresh();
  }

  Future<void> bindAllDevices() async {
    try {
      if (selectedDevices.isEmpty) {
        print('⚠️ [bindAllDevices] No devices selected');
        ToastUtils.showError(AppLocalizations.of(Get.context!)!.translate('no_devices_to_bind'));
        return;
      }

      print('🔄 [bindAllDevices] Starting device binding process');
      print('📱 [bindAllDevices] Selected devices: ${selectedDevices.join(", ")}');
      print('📍 [bindAllDevices] Current group: $currentGroup');
      print('🏷️ [bindAllDevices] Type: $type, From: $from');

      await Get.find<DeviceController>().addDevice(
        selectedDevices,
        group: currentGroup,
        type: type,
        from: from,
      );

      if (from == 'cast') {
        print('🎬 [bindAllDevices] Processing cast validation');
        Get.find<CastController>().validateDeviceResolution([
          bluetoothManager.deviceInfoMap[bluetoothManager.nfcScanResults.first.id]!,
        ]);
      }

      print('✅ [bindAllDevices] Device binding completed successfully');
      Get.back();
    } catch (e) {
      print('❌ [bindAllDevices] Error during device binding: $e');
      ToastUtils.showError('${e.toString()}');
    }
  }
}
